package com.arunsawad.ilertu.common;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

import android.os.AsyncTask;
import android.util.Log;

public class RequestTask extends AsyncTask<String, Void, String> {
	private AsyncActivity listener;

	public void setListener(AsyncActivity listener) {
		this.listener = listener;
	}

	@Override
	protected String doInBackground(String... params) {
		// params[0]: url
		// params[1]: message
		return SendRequest(params[0], params[1]);
	}

	protected void onPreExecute() {

	}

	protected void onPostExecute(String result) {
		super.onPostExecute(result);
		listener.onRequestCompleted(result);
	}

	public String SendRequest(String address, String msg) {
		String responseXML = null;
		try {
			URL url = new URL(address);
			URLConnection connection = url.openConnection();
			HttpURLConnection httpConn = (HttpURLConnection) connection;

			byte[] requestXML = msg.getBytes();

			// Set the appropriate HTTP parameters.
			httpConn.setRequestProperty("Content-Length",
					String.valueOf(requestXML.length));
			httpConn.setRequestProperty("Content-Type",
					"text/xml; charset=utf-8");
			httpConn.setRequestMethod("POST");
			httpConn.setDoOutput(true);
			httpConn.setDoInput(true);

			// Send the String that was read into postByte.
			OutputStream out = httpConn.getOutputStream();
			out.write(requestXML);
			out.close();

			// Read the response and write it to standard out.
			InputStreamReader isr = new InputStreamReader(
					httpConn.getInputStream());
			BufferedReader br = new BufferedReader(isr);
			String temp;
			String tempResponse = "";

			// Create a string using response from web services
			while ((temp = br.readLine()) != null)
				tempResponse = tempResponse + temp;
			responseXML = tempResponse;
			// responseXML = testStr;
			br.close();
			isr.close();
		} catch (java.net.MalformedURLException e) {
			Log.w("E", "Error in postRequest(): Secure Service Required");
		} catch (Exception e) {
			Log.w("E", "Error in postRequest(): " + e.getMessage());
		}
		return responseXML;
	}
}